package com.xiangxiao.rpan.storage.service.impl;

import com.xiangxiao.rpan.storage.constant.GlobalConsts;
import com.xiangxiao.rpan.storage.constant.ResponseCode;
import com.xiangxiao.rpan.storage.constant.ResponseMessage;
import com.xiangxiao.rpan.storage.core.*;
import com.xiangxiao.rpan.storage.dao.TUploadedRecordMapper;
import com.xiangxiao.rpan.storage.entity.TUploadedRecord;
import com.xiangxiao.rpan.storage.exception.StorageExcetion;
import com.xiangxiao.rpan.storage.service.DownloadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/12/5 14:14
 */
@Slf4j
@Service
public class DownloadServiceImpl implements DownloadService {
  private static final String UTF_8 = "UTF-8";
  @Qualifier(value = "cacheManager")
  private CacheManager cacheManager;

  @Autowired
  @Qualifier(value = "downloadFileToolManager")
  private DownloadFileToolManager downloadFileToolManager;

  @Autowired
  @Qualifier(value = "storageManager")
  private StorageManager storageManager;

  @Resource
  private TUploadedRecordMapper tUploadedRecordMapper;

  @Override
  public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
    String filemd5 = request.getParameter("filemd5");
    TUploadedRecord tUploadedRecord = tUploadedRecordMapper.selectByFileMD5(filemd5);
    if (tUploadedRecord == null) {
      throw new StorageExcetion(ResponseMessage.FILE_NOT_EXIST, ResponseCode.FILE_NOT_EXIST);
    }
    Long fileSize = tUploadedRecord.getFileSize();
    if (fileSize < GlobalConsts.FILE_SPLIT_SIZE) {
      this.downloadSmallFile(request, response, tUploadedRecord);
    } else {
      this.downloadBigfile(request, response, tUploadedRecord);
    }
  }

  @Override
  public void downloadSmallFile(HttpServletRequest request, HttpServletResponse response, TUploadedRecord tUploadedRecord)
      throws UnsupportedEncodingException {
    try {
      downloadFileToolManager.readStreamToFile(tUploadedRecord.getFilePath(), response);
    } catch (IOException e) {
      log.info("downloadSmallFile failed", e);
      e.printStackTrace();
    }
  }

  @Override
  public void downloadBigfile(HttpServletRequest request, HttpServletResponse response, TUploadedRecord tUploadedRecord) {

  }
}
